package com.shekhar.movieverdict.scheduler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

import com.shekhar.movieverdict.domain.Movie;
import com.shekhar.movieverdict.service.MovieService;
import com.shekhar.movieverdict.service.TweetService;

@Component
public class TweetsArchiver {

    static {
        ConfigurationBuilder builder = new ConfigurationBuilder()
                .setDebugEnabled(true)
                .setOAuthConsumerKey("D5QsM4lVmWaY71FAje5yA")
                .setOAuthConsumerSecret(
                        "XcumieVWKz466he7Fi9BgeowyQKC4yTxEj9IXRFFg")
                .setOAuthAccessToken(
                        "66993334-1Q3bdTQuhygGHNeNUgdmtJEjP5grTAsrIemZ8ku7T")
                .setOAuthAccessTokenSecret(
                        "XTNQdVaPfdFcQq6E30WHX6E69j5Ke3gVeU3va7brOYc");
    }

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private MovieService movieService;

    @Autowired
    private TweetService tweetService;
    private long count;

    @Scheduled(fixedRate = 180000l)
    public void acrhiveTweets() throws Exception {
        count++;
        logger.info("Running Archiving Job .... Count ... " + count);
        TwitterFactory factory = new TwitterFactory();
        Twitter twitter = factory.getInstance();

        List<Movie> scheduledMovies = movieService.findAllScheduledMovies();
        if (CollectionUtils.isEmpty(scheduledMovies)) {
            logger.info("No Scheduled Movie Found.. So Waiting Till Next Run...");
        }
        for (Movie scheduledMovie : scheduledMovies) {
            String searchTerms = scheduledMovie.getSearchTerms();
            String[] searchTermArray = StringUtils.split(searchTerms, ",");
            for (String searchTerm : searchTermArray) {
                searchTerm = escapeIfSearchStringContainSpace(searchTerm);
                Query query = new Query();
                query.setRpp(100);
                query.setQuery(searchTerm);
                QueryResult queryResult = twitter.search(query);
                List<Tweet> tweets = queryResult.getTweets();
                logger.info("Found tweets before filtering ... "
                        + tweets.size());

                List<Tweet> filteredTweets = filterTweets(tweets);
                logger.info("Found tweets after filtering ... "
                        + filteredTweets.size());
                for (Tweet tweet : filteredTweets) {
                    com.shekhar.movieverdict.domain.Tweet domainTweet = new com.shekhar.movieverdict.domain.Tweet();
                    domainTweet.setCreatedOn(tweet.getCreatedAt());
                    domainTweet.setLocaltion(tweet.getLocation());
                    domainTweet.setText(tweet.getText());
                    domainTweet.setTweetId(tweet.getId());
                    domainTweet.setPersistedOn(new Date());
                    domainTweet.setMovieTitle(scheduledMovie.getTitle());
                    domainTweet.setOwnerId(tweet.getFromUserId());
                    tweetService.saveTweet(domainTweet);
                }
            }
        }
    }

    private List<Tweet> filterTweets(List<Tweet> tweets) {
        List<Tweet> filteredTweets = new ArrayList<Tweet>();
        for (Tweet tweet : tweets) {
            List<com.shekhar.movieverdict.domain.Tweet> foundTweets = tweetService
                    .findAllTweetsByTweetId(tweet.getId());
            if (!CollectionUtils.isEmpty(foundTweets)) {
                continue;
            }
            filteredTweets.add(tweet);
        }
        return filteredTweets;
    }

    static String escapeIfSearchStringContainSpace(String searchTerm) {
        if (StringUtils.containsWhitespace(searchTerm)) {
            searchTerm = "\"" + searchTerm + "\"";
        }
        return searchTerm;
    }

    public static void main(String[] args) throws Exception {
        TwitterFactory factory = new TwitterFactory();
        Twitter twitter = factory.getInstance();
        String searchTerm = "Don 2";
        searchTerm = escapeIfSearchStringContainSpace(searchTerm);
        Query query = new Query();
        query.setRpp(100);
        query.setQuery(searchTerm);
        QueryResult queryResult = twitter.search(query);
        List<Tweet> tweets = queryResult.getTweets();
        for (Tweet tweet : tweets) {
            System.out.println(tweet.getText());
        }
    }
}
